<?php

class TTT extends Obj {
	public $field;
	public $player1;
	public $player2;
	public $current;
	public $winner;

	public function TTT() {
		$this->reset();
	}

	public function reset(){
		$this->player1 = false;
		$this->player2 = false;
		$this->restart();
	}

	public function restart(){
		$this->field = array(0,0,0,
			                 0,0,0,
			                 0,0,0);
		$this->current = 1;
		$this->winner = 0;
	}

	public function register($userId) {
		if($this->player1 == false) {
			$this->player1 = $userId;
		} else if ($this->player2 == false && $this->player1 != $userId) {
			$this->player2 = $userId;
			$this->current = 1;
		}
	}

	public function unregister($userId) {
		if($this->player1 == $userId) {
			$this->player1 = false;
			$this->restart();
		} else if ($this->player2 == $userId) {
			$this->player2 = false;
			$this->restart();
		}
	}

	
	public function amICurrent($id){
		return ($id == $this->player1 && $this->current == 1 ) || ($id == $this->player2 && $this->current == 2 );
	}

	private function check3($x1, $x2, $x3){
		if($this->field[$x1]!=0 && $this->field[$x1]==$this->field[$x2] && $this->field[$x2]==$this->field[$x3]){
			return $this->field[$x1];
		}
		return 0;
	}

	private function checkWin(){
		$w = $this->check3(0,1,2);
		if($w==0) $w = $this->check3(3,4,5);
		if($w==0) $w = $this->check3(6,7,8);
		
		if($w==0) $w = $this->check3(0,3,6);
		if($w==0) $w = $this->check3(1,4,7);
		if($w==0) $w = $this->check3(2,5,8);

		if($w==0) $w = $this->check3(0,4,8);
		if($w==0) $w = $this->check3(2,4,6);
		if($w!=0){
			$this->winner = $w;
			$this->curent = 0;
		}
	}

	public function getWinnerUser() {
		if($this->winner==0) return false;
		if($this->winner==1) {
			return DB::load($this->player1);
		} else {
			return DB::load($this->player2);
		}
	}

	public function doMove($usrId, $ix){
		if(isset($this->field[$ix]) && $this->field[$ix] == 0 && (($usrId == $this->player1 && $this->current==1) || ($usrId == $this->player2 && $this->current == 2))) {
			$this->field[$ix] = $this->current;
			$this->current = 3 - $this->current;
			$this->checkWin();
		} 
	}

	public function hash() {
		$ret = 31;
		for($i=0;$i<9;$i++) {
			$ret *= 31;
			$ret += $this->field[$i];
		}
		$ret = $ret * 31 + $this->current;
		$ret = $ret * 31 + $this->winner;
		return $ret;
	}

}

?>